import { loginApi } from '@/api/system/login'
import { getToken, setToken, removeToken } from '@/utils/auth'

// 用户信息
const state = {
  token: getToken(),
  name: '',
  roles: [],
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
}

const actions = {
  // user login
  login({ commit, state }, userInfo: any) {
    const { username, password } = userInfo

    return new Promise<void>((resolve, reject) => {
      loginApi({ username: username.trim(), password: password })
        .then(({ data: { token } }) => {
          commit('SET_TOKEN', token)
          setToken(token)
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
}
